package com.ruoyi.asset.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.asset.mapper.AssetFlowStepMapper;
import com.ruoyi.asset.domain.AssetFlowStep;
import com.ruoyi.asset.service.IAssetFlowStepService;

import javax.annotation.PostConstruct;

/**
 * 审核流程Service业务层处理
 * 
 * @author yepanpan
 * @date 2024-12-25
 */
@Service
public class AssetFlowStepServiceImpl implements IAssetFlowStepService 
{
    public static final String CACHE_MAP = "asset_flow_step";
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private AssetFlowStepMapper assetFlowStepMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysPostMapper sysPostMapper;


    @PostConstruct
    public int reCache(){
        redisCache.deleteObject(CACHE_MAP);
        return 0;
    }

    /**
     * 查询审核流程
     * 
     * @param id 审核流程主键
     * @return 审核流程
     */
    @Override
    public AssetFlowStep selectAssetFlowStepById(Long id)
    {

        return assetFlowStepMapper.selectAssetFlowStepById(id);
    }

    /**
     * 查询审核流程列表
     *
     * @param typeId 流程主键
     * @return 审核流程集合
     */
    @Override
    public List<AssetFlowStep> selectAssetFlowStepList(Long typeId){
        String key = "type_"+typeId;
        List<AssetFlowStep> stepList = redisCache.getCacheMapValue(CACHE_MAP, key);
        if(StringUtils.isNotEmpty(stepList)){
            return stepList;
        }

        AssetFlowStep fsc = new AssetFlowStep();
        fsc.setTypeId(typeId);
        stepList = assetFlowStepMapper.selectAssetFlowStepList(fsc);
        if(StringUtils.isNotEmpty(stepList)){
            redisCache.setCacheMapValue(CACHE_MAP, key, stepList);
        }
        return stepList;
    }

    /**
     * 查询审核流程列表
     * 
     * @param assetFlowStep 审核流程
     * @return 审核流程
     */
    @Override
    public List<AssetFlowStep> selectAssetFlowStepList(AssetFlowStep assetFlowStep)
    {
        List<AssetFlowStep> stepList =  assetFlowStepMapper.selectAssetFlowStepList(assetFlowStep);
        if(StringUtils.isEmpty(stepList)){
            return stepList;
        }

        for(AssetFlowStep step:stepList){
            if(StringUtils.isEmpty(step.getTargets())){
                continue;
            }
            String[] ids = step.getTargets().split(",");
            String names = "";
            if(step.getType().equalsIgnoreCase(AssetFlowStep.TYPE_USER)){
                for(String id:ids){
                    SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(id));
                    if(sysUser != null){
                        names += ","+sysUser.getNickName();
                    }
                }
            }else if(step.getType().equalsIgnoreCase(AssetFlowStep.TYPE_ROLE)){
                for(String id:ids){
                    SysRole sysRole = sysRoleMapper.selectRoleById(Long.parseLong(id));
                    if(sysRole != null){
                        names += ","+sysRole.getRoleName();
                    }
                }
            }else if(step.getType().equalsIgnoreCase(AssetFlowStep.TYPE_POST)){
                for(String id:ids){
                    SysPost sysPost = sysPostMapper.selectPostById(Long.parseLong(id));
                    if(sysPost != null){
                        names += ","+sysPost.getPostName();
                    }
                }
            }
            step.setTargetsName(names.length() > 1 ? names.substring(1) : "");
        }
        return stepList;
    }

    /**
     * 新增审核流程
     * 
     * @param assetFlowStep 审核流程
     * @return 结果
     */
    @Override
    public int insertAssetFlowStep(AssetFlowStep assetFlowStep)
    {
        if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_DEPT)
                || assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_PARENT_DEPT)){
            assetFlowStep.setTargets("");
        }
        return assetFlowStepMapper.insertAssetFlowStep(assetFlowStep) + reCache();
    }

    /**
     * 修改审核流程
     * 
     * @param assetFlowStep 审核流程
     * @return 结果
     */
    @Override
    public int updateAssetFlowStep(AssetFlowStep assetFlowStep)
    {
        if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_DEPT)
                || assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_PARENT_DEPT)){
            assetFlowStep.setTargets("");
        }
        return assetFlowStepMapper.updateAssetFlowStep(assetFlowStep) + reCache();
    }

    /**
     * 测试配置是否合理
     * @param typeId
     */
    public void test(Long typeId){

    }

    /**
     * 批量删除审核流程
     * 
     * @param ids 需要删除的审核流程主键
     * @return 结果
     */
    @Override
    public int deleteAssetFlowStepByIds(Long[] ids)
    {
        return assetFlowStepMapper.deleteAssetFlowStepByIds(ids) + reCache();
    }

    /**
     * 删除审核流程信息
     * 
     * @param id 审核流程主键
     * @return 结果
     */
    @Override
    public int deleteAssetFlowStepById(Long id)
    {
        return assetFlowStepMapper.deleteAssetFlowStepById(id) + reCache();
    }

    /**
     * 查询节点审核人
     * @param typeId 流程
     * @param typeId 当前节点
     * @param userId 流程用户
     * @return
     */
    public List<SysUser> selectStepUser(Long typeId, Long stepId, Long userId){
        AssetFlowStep assetFlowStep = selectAssetFlowStepById(stepId);
        if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_DEPT)){
            SysRole role = sysRoleMapper.checkRoleKeyUnique("deptAdmin");
            if(role == null){
                return null;
            }
            SysUser user = sysUserMapper.selectUserById(userId);
            SysUser uc = new SysUser();
            uc.setDelFlag("0");
            uc.setDeptId(user.getDeptId());
            uc.setRoleId(role.getRoleId());
            return sysUserMapper.selectUserList(uc);
        }else if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_PARENT_DEPT)){
            SysRole role = sysRoleMapper.checkRoleKeyUnique("deptAdmin");
            if(role == null){
                return null;
            }
            SysUser user = sysUserMapper.selectUserById(userId);
            SysDept dept = sysDeptMapper.selectDeptById(user.getDeptId());
            if(dept.getParentId() == null || dept.getParentId().equals(0L)){
                return null;
            }
            SysUser uc = new SysUser();
            uc.setDelFlag("0");
            uc.setDeptId(dept.getDeptId());
            uc.setRoleId(role.getRoleId());
            return sysUserMapper.selectUserList(uc);
        }else if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_USER)){
            if(StringUtils.isEmpty(assetFlowStep.getTargets())){
                return null;
            }
            List<SysUser> userList = new ArrayList<>();
            String[] userIds = assetFlowStep.getTargets().split(",");
            for(String id:userIds){
                if(StringUtils.isEmpty(id)){
                    continue;
                }
                userList.add(sysUserMapper.selectUserById(Long.parseLong(id)));
            }
            return userList;
        }else if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_ROLE)){
            if(StringUtils.isEmpty(assetFlowStep.getTargets())){
                return null;
            }
            SysUser uc = new SysUser();
            uc.setDelFlag("0");

            String[] roleIds = assetFlowStep.getTargets().split(",");
            Long[] roleId = new Long[roleIds.length];
            for(int i=0;i<roleIds.length;i++){
                roleId[i] = Long.parseLong(roleIds[i]);
            }
            uc.setRoleIds(roleId);
            return sysUserMapper.selectUserList(uc);
        }else if(assetFlowStep.getType().equalsIgnoreCase(AssetFlowStep.TYPE_DEPT)){
            if(StringUtils.isEmpty(assetFlowStep.getTargets())){
                return null;
            }
            SysUser uc = new SysUser();
            uc.setDelFlag("0");

            String[] postIds = assetFlowStep.getTargets().split(",");
            Long[] postId = new Long[postIds.length];
            for(int i=0;i<postIds.length;i++){
                postId[i] = Long.parseLong(postIds[i]);
            }
            uc.setPostIds(postId);
            return sysUserMapper.selectUserList(uc);
        }else{
            return null;
        }
    }
}
